<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" title="价签申请" color="#000000" backgroundColor="#FFFFFF" :storeName="sUserStoreName"
                :storeId="sUserStore" @onClickStore="clickStore" :option="nbOption" @menuFunc="onClickMenuFunc"/>
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码"
                      leftIcon="icon-saoyisao"
                      @confirm="searchConfirm" @leftIconClick="scanCode" radius="30" :showFilter="true">
        <template v-slot:searchFields>
          <view class="search-fields">
            <view class="center">
              <eui-card-input
                  key="c_mk_dt_s"
                  class="search-field"
                  v-model="formData.c_mk_dt_s"
                  title="开始日期"
                  placeholder="请选择申请开始日期"
                  type="date"
                  rightIconType="right"
                  :displayable="displayable"
              />
              <eui-card-input
                  key="c_mk_dt_e"
                  class="search-field"
                  v-model="formData.c_mk_dt_e"
                  title="结束日期"
                  placeholder="请选择申请结束日期"
                  type="date"
                  rightIconType="right"
                  :displayable="displayable"
              />
              <eui-card-input
                  key="c_status"
                  class="search-field"
                  v-model="formData.c_status"
                  title="单据状态"
                  placeholder="请选择单据状态"
                  type="multi"
                  :range="statusList"
                  alignType="left"
                  :displayable="displayable"
              />
              <eui-card-input
                  v-model="formData.c_mk_userno"
                  title="申请人"
                  @iconClick="clickUser"
                  rightIconType="right"
                  placeholder="请选择申请人"
                  type="textname2"
                  :displayable="displayable"
                  :name="getName('rdsUsers', formData.c_mk_userno)"
                  key="c_mk_userno"
              />
            </view>
            <view class="bottom flex-1 flex">
              <eui-button type="max2" title="重置" singleTag="reset" @buttonClick="confirm"></eui-button>
              <eui-button type="max" title="确认" singleTag="fix" @buttonClick="confirm"></eui-button>
            </view>
          </view>
        </template>
      </eui-search-bar>
    </view>
    <view class="main-view" :style="{ height: listHeight + 'rpx' }">
      <eui-virtual-list @onRefresh="getData" @lower="templateLower" :refresher="true" @itemClick="listItemClick"
                        :origList="dataList" type="list">
        <template v-slot:list="scope">
          <eui-text v-model="scope.c_sku_order" type="name2"
                    title="品项数:" />
          <eui-text v-model="scope.c_adno" :name="getRelatedName('rdsDeparts', scope.c_adno)" type="titlename2"
                    title="部门:" />
          <eui-text v-model="scope.c_mk_userno" :name="getRelatedName('rdsUsers',scope.c_mk_userno)"
                    type="titlename2" title="制单人:" />
          <eui-text v-model="scope.c_mk_dt" type="rdstime2" />
          <eui-text v-model="scope.c_print_userno" :name="getRelatedName('rdsUsers',scope.c_print_userno)"
                    type="titlename2" title="打印人:" />
          <eui-text v-model="scope.c_print_dt" type="rdstime2" />
        </template>
      </eui-virtual-list>
    </view>
  </view>
</template>

<script setup type="ts">
import Enjoy from '@/common/enjoy';
import service from '@/common/service';
import { init } from '@/hooks/init';
import { getRdsUrl, rdsRequest } from '@/hooks/rdsServices';
import { useMainStore } from '@/store/modules/store';
import { useLoginStore } from '@/store/modules/useLoginStore';
import { validateStores } from '@/hooks/useValidateMethod';
import { onLoad } from '@dcloudio/uni-app';
import dayjs from 'dayjs';
import { ref } from 'vue';
import dateRangUtil from '../../../common/dateRangUtil';
import { getDictList, getRelatedName } from '../components/RelatedName.js';

const mainStore = useMainStore();
const LoginStore = useLoginStore();
const rdsUrl = getRdsUrl();

// 定义响应式数据
const sUserStore = ref(''); // 用户默认机构编码
const sUserStoreName = ref(''); // 用户默认机构名称
const sUser = ref(''); // 当前用户编码
const dataList = ref([]);
const CurrentPage = ref(1); // 第几页
const PageSize = ref(10); // 每页10条
const RowsCount = ref(0); // 总条数
const PageCount = ref(1); // 总页数
const current = ref(0);
const listHeight = ref(300);  //列表高度

const searchText = ref('');
const extendNavBarMenus = ref([]);

const displayable = ref(false); // true允许页面编辑

// 查询表单
const formData = ref({
  c_mk_dt_s: dateRangUtil.getLast7Day()[0],
  c_mk_dt_e: dateRangUtil.getLast7Day()[1],
  c_mk_userno: '',
  c_status: '0,3', // 默认显示未审核
});

const height = ref(0);

// 系统参数，字典
const sysConfig = ref({
  c_status: {}, // 单据状态
});

const statusList = ref([]); // 查询条件状态下拉框

const selectType = ref('');
const ISSearch = ref(false);

// 获取组件引用
const EuiNavBar = ref(null);
const RdsSearchBar = ref(null);

const nbOption = ref({
  items: [
    {title: '申请', onClick: 'onClickNewCount', icon: 'plusempty'},
  ]
})

// 监听

// 页面加载时执行
onLoad(async () => {
  await init();
  await getSysConfig();
  const {loginInfo} = mainStore;
  if (!loginInfo.sUserStore) {
    if (EuiNavBar.value) {
      EuiNavBar.value.onClickStore();
    }
    return;
  }
  setDefault();
  getData();
});

// 设置默认值
const setDefault = () => {
  const {loginInfo} = mainStore;
  sUserStore.value = loginInfo.sUserStore;
  sUserStoreName.value = loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
  formData.value.c_mk_userno = loginInfo.sUser;
};

// 点击扫描图标跳转打开摄像头
const scanCode = () => {
  uni.scanCode({
    success: function (res) {
      if (res.result != '' && res.result != undefined && res.result != null) {
        searchText.value = res.result;
        getData();
      }
    },
  });
};

// 获取系统配置
const getSysConfig = async () => {
  const c_status_list = await getDictList('MO类单据状态');
  c_status_list.forEach(e => {
    sysConfig.value.c_status[e.c_id] = e.c_name;
    statusList.value.push({
      text: e.c_name,
      value: e.c_id,
      checked: formData.value.c_status.includes(e.c_id),
    });
  });

};

// 选择框点击事件
const clickStore = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  parms.SelectionType = '机构选择';
  parms.SelectedItems = sUserStore.value;
  Enjoy.OpenDialog(parms);
};

// 加载列表数据
const getData = async (isLoadMore = false) => {
  if (!isLoadMore) {
    CurrentPage.value = 1;
  }
  const objectData = {
    IsNotPage: false,
    CurrentPage: CurrentPage.value,
    PageSize: PageSize.value,
    UserNo: sUser.value,
    WhereList: [
      {
        c_col: 'c_store_id',
        c_oper: '等于',
        c_value: sUserStore.value,
        c_logic: '而且',
      },
      {
        c_col: 'c_mk_dt',
        c_oper: '大于等于',
        c_value: formData.value.c_mk_dt_s,
        c_col_dtype: 'System.DateTime',
        c_logic: '而且',
      },
      {
        c_col: 'c_mk_dt',
        c_oper: '小于等于',
        c_value: formData.value.c_mk_dt_e,
        c_col_dtype: 'System.DateTime',
        c_logic: '而且',
      },
      {
        c_col: 'c_status',
        c_oper: '包含',
        c_value: formData.value.c_status,
        c_logic: '而且',
      },
      {
        c_col: 'c_mk_userno',
        c_col_dtype: 'System.String',
        c_left: '',
        c_oper: '=',
        c_logic: '而且',
        c_right: '',
        c_value: formData.value.c_mk_userno,
        c_group: '高级',
      },
    ],
  };

  if (searchText.value) {
    if (/^\d+$/.test(searchText.value)) {
      objectData.WhereList.push({
        c_col: 'c_gcode',
        c_oper: '等于',
        c_value: searchText.value,
        c_logic: '而且',
      });
    } else {
      objectData.WhereList = [
        {
          c_col: 'c_store_id',
          c_oper: '等于',
          c_value: sUserStore.value,
          c_logic: '而且',
        },
        {
          c_col: 'c_id',
          c_oper: '等于',
          c_value: searchText.value,
          c_logic: '而且',
        },
      ];
    }
  }

  service.enjoyShowLoading('正在加载...');
  const result = await rdsRequest(rdsUrl.bcApi, '商品价签打印申请单', 'EnjoyQueryList', objectData);

  CurrentPage.value = result.CurrentPage;
  PageSize.value = result.PageSize;
  RowsCount.value = result.RowsCount;
  PageCount.value = result.PageCount;

  if (result.CurrentPage === 1) {
    dataList.value = result.ReturnObject;
  } else {
    dataList.value = dataList.value.concat(result.ReturnObject);
  }
  dataList.value.forEach(x => {
    x.c_date = dayjs(x.c_mk_dt).format('MM/DD');
  })

  // 如果商品扫描出的盘单列表只有一条记录时，直接跳转到盘点详情页面
  if (searchText.value && result.ReturnObject.length === 1) {
    listItemClick(result.ReturnObject[0], searchText.value);
  }

  service.enjoyHideLoading();
};

// 上拉加载更多
const templateLower = () => {
  if (CurrentPage.value < PageCount.value) {
    CurrentPage.value += 1;
    getData(true);
  }
};

// 选择用户
const clickUser = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChangedUser;
  parms.SelectionType = '人员选择';
  parms.SelectedItems = formData.value.c_mk_userno;
  Enjoy.OpenDialog(parms);
};

// 搜索点击
const searchClick = () => {
  ISSearch.value = !ISSearch.value;
};

// 回调方法：切换机构/或其他条件
const SelectionChanged = async (event) => {
  if (event.SelectionType == '机构选择') {
    // 更新机构信息
    sUserStoreName.value = event.BackParms.Value;
    sUserStore.value = event.BackParms.Key;
    await getData();
  } else if (event.type === 'c_userno') {
    formData.value.c_mk_userno = event.c_userno;
  }
};

const SelectionChangedUser = async (event) => {
  formData.value.c_mk_userno = event.BackParms.Key;
};

// 页面回调方法
const searchConfirm = async (e) => {
  if (!e) {
    return;
  }
  searchText.value = e.value;
  await getData();
};

// 列表项点击跳转到盘点录入页面
const listItemClick = (e, c_gcode = '') => {
  uni.navigateTo({
    url: `./edit?pid=${e.item.c_id}`,
  });
};

// 筛选条件确认
const confirm = (t, num) => {
  let {singleTag} = t;
  const {loginInfo} = mainStore;
  switch (singleTag) {
    case 'reset':
      formData.value.c_mk_dt_s = dateRangUtil.getLast7Day()[0];
      formData.value.c_mk_dt_e = dateRangUtil.getLast7Day()[1];
      formData.value.c_mk_userno = loginInfo.sUser;
      formData.value.c_status = '0,3';
      statusList.value.forEach(item => {
        item.checked = item.value === '0' || item.value === '3';
      });
      break;
    case 'fix':
      getData();
      // 关闭弹出层
      RdsSearchBar.value.closeDrawer();
      break;
  }
};

// 新增单据
const onClickMenuFunc = async (e) => {
  switch (e) {
    case 'onClickNewCount':
      setTimeout(() => {
        EuiNavBar.value.closeDrawer();
      },1200);
      // 检查当前机构是否为 分店或配送中心，否则不允许新建
      const result = await validateStores(
          { fieldName: 'c_store_id', newValue: sUserStore.value },
          { ischecklimit: true, firstValueMode: true }
      );
      if (!['2', '3'].includes(result.c_type)) {
        uni.showToast({
          title: '当前机构不允许新增价签打印申请单,请切换至分店或配送中心!',
          icon: 'none',
          duration: 3000,
        });
        return;
      }
      uni.navigateTo({
        url: './edit?storeId=' + sUserStore.value
      });
      break;
  }
}

// 自定义id展示
const customId = (c_id, c_count_dt) => {
  return `${dayjs(c_count_dt).format('MM/DD')} ${c_id}`;
};

const getName = (key, value) => {
  if (!value) {
    return '';
  }
  let list = [];
  value.split(',').map(item => {
    list.push('[' + item + ']' + (getRelatedName(key, item) || key));
  });
  return list.join(',');
};

</script>

<style lang="scss" scoped>
@import '../../../main.scss';

.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}

.top-view {
  width: 100%;
  height: 88rpx;
  background: #FFFFFF;
  margin-bottom: 20rpx;
}

.main-view {
  flex: 1;
  flex-direction: column;
}

// start 重置标题栏右侧样式 展示当前用户所属门店
::v-deep .uni-navbar__header-btns-right {
  position: relative;
  height: 100%;
}

::v-deep .uni-nav-bar-right-text {
  position: absolute;
  top: 0;
  right: 0;
  color: #aaffff;
  text-align: center;
  max-width: 200rpx;
  margin-right: 30rpx;
  font-size: 0.8rem;
  padding-top: 0.1rem;
  justify-content: center;
  align-items: center;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

// end  重置标题栏右侧样式 展示当前用户所属门店

.footer {
  margin: 0;
  flex: 7;

  ::v-deep .m-list-template-list {
    //height: auto!important;
  }
}

// start 自定义更多按钮
// 复制 RdsNavBar
.custom-menu {
  border-top: 1px solid rgba(0, 0, 0, .1);
  display: flex;
  flex: 1;
  width: 100%;
  justify-content: flex-start;
}

.popup-icon-btn {
  display: flex;
  padding: 10px;
  margin: 5px;
  color: #333333;
  text-align: center;
  flex-direction: column;
}

.popup-icon-btn uni-icon {
  margin: 0 auto;
  background: #ffffff;
  border-radius: 50%;
  font-size: 1.2em;
  width: 42px;
  height: 42px;
  line-height: 42px;
  text-align: center;
}

.popup-icon-btn uni-text {
  font-size: 0.8em;
  padding: 0.2em 0;
  line-height: 1.4em;
  width: 52px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

// 业务自定义
.icon_new_count {
  color: #00aaff;
}

// end 自定义更多按钮

.search-fields {
  width: 100%;
  background: #FFFFFF;
  position: relative;

  .bottom {
    background: #ffffff;
    border-top: 1rpx solid $uni-line-color;
    display: flex;
    justify-content: center;
    padding: 20rpx;
  }
}

// end 查询筛选

// 列表项自定义
.custom-id {
  z-index: 1;
  position: relative;
  line-height: 1.2em;
}

.custom-id::before {
  position: absolute;
  z-index: 0;
  content: ' ';
  width: 2.5em;
  height: 1.2em;
  background: rgba(153, 255, 102, 0.2);
  top: 0;
  left: 0;
}

// end 列表项自定义

</style>
